import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
//引入弹窗提示
import { ElMessage } from "element-plus";

//设置一个数组 用来设置菜单地址
export const pathArr = [
  {
    path: "/menu",
    component: () => import('../views/menu/index.vue'),
    meta: {
      title: "菜单管理"
    }
  }, {
    path: "/role",
    component: () => import('../views/role/index.vue'),
    meta: {
      title: "角色管理"
    }
  }, {
    path: "/user",
    component: () => import('../views/user/index.vue'),
    meta: {
      title: "管理员管理"
    }
  }, {
    path: "/cate",
    component: () => import('../views/cate/index.vue'),
    meta: {
      title: "商品分类"
    }
  },
];


const routes: Array<RouteRecordRaw> = [
  {
    path: "/login",
    component: () => import('../pages/login.vue')
  }, {
    path: "/index",
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: "/home",
        component: () => import('../views/home.vue'),
        meta:{
          title:'首页'
        }
      },
      ...pathArr
      , {
        path: "",
        redirect: '/home'
      }
    ]
  }, {
    path: "/:pathMatch(.*)",
    redirect: "/home"
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

//全局登录拦截
router.beforeEach((to, from, next) => {
  document.title = to.meta.title + '';

  //是否是去的登录
  if (to.path == '/login') {
    next();
    return
  };
  let data: any = sessionStorage.getItem('userInfo');
  //在判断 是否有登录验证
  if (data) {
    //这是权限拦截  在登录返回的数据里面查找 是否有权限访问的页面
    let url = JSON.parse(data).menus_url.some((val: string) => {
      return to.path == val
    });

    if (!url && to.path != "/home") {
      ElMessage.error('您没有权限，已为您重新跳转');
      next('/home');
      return;
    }
    next();
    return;
  };

  next('/login');
})

export default router
